package pers.cz.node;

import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.context.SecurityContextHolder;
import pers.cz.exception.ExceptionUtil;
import pers.cz.mxgraph.MxCell;
import pers.cz.session.UserUtils;
import pers.cz.thread.ThreadUtils;
import pers.cz.websocket.MessagePushSocketUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @program: Reids
 * @description: 抽象节点
 * 节点应具有的方法：
 * 1、校验节点的合法性
 * 2、获取节点的参数
 * 3、判断节点的状态
 * 4、执行节点并通知前端
 * 5、获取执行结果
 * 6、
 * @author: Cheng Zhi
 * @create: 2023-01-08 19:43
 **/
public abstract class AbstractNode implements Node{

    Logger logger = LoggerFactory.getLogger(AbstractNode.class);

    public MxCell mxCell;

    private Runnable runnable;

    /**
     * 自定义业务参数传递
     */
    public Map<String, Object> map = new ConcurrentHashMap<String, Object>();

    /**
     * 整个流程理论上只打开一个浏览器即可
     */
    private static RemoteWebDriver driver;

    public AbstractNode(MxCell mxCell) {
        this.mxCell = mxCell;
    }
    // 支持动态扩展
    public void run(NodeCallBack callBack) {
        map.put(NodeRunState.RUN_TYPE, NodeRunState.RUN_SUCCESS); // 默认运行状态为成功。
        try {
            runNode(callBack);
            map.put(NodeRunState.RUN_TYPE, NodeRunState.RUN_SUCCESS);
            MessagePushSocketUtils.sendMsg(MessagePushSocketUtils.AUTOUI_MESSAGE, mxCell.getId() + "|" + NodeRunState.NODE_TYPE_SUCCESS, 0);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            MessagePushSocketUtils.sendMsg(MessagePushSocketUtils.AUTOUI_MESSAGE, mxCell.getId() + "|" + NodeRunState.NODE_TYPE_FAIL, 0);
            map.put(NodeRunState.RUN_TYPE, NodeRunState.RUN_FAIL);
        }
        callBack.callBack(map);
        // 每个节点运行完成后默认休眠一段事件
        sleep();
    }

    public void setDriver(RemoteWebDriver driverObj) {
        driver = driverObj;
    }

    public RemoteWebDriver getDriver() {
        return driver;
    }

    public abstract void runNode(NodeCallBack callBack) throws Exception;
    /**
     * 检验参数
     */
    public abstract void verify();

    public void sleep() {
        sleep(10000L);
    }

    public void sleep(Long millis) {
        ThreadUtils.doSleep(millis);
    }
}
